#include "stdafx.h"
#include "fuUtils.h"

#include <wx/fs_zip.h>
#include <wx/filesys.h>
#include <wx/wfstream.h>
#include <wx/mstream.h>
#include <wx/dir.h>	// wxDirTraverser

#include <memory>

wxBitmap LoadBitmapFromZipFile( const wxString & zipfile, const wxString& name )
{
    wxString file_res	= wxString::Format(_T("%s#zip:%s"),_T("./") + zipfile,name);

    std::auto_ptr<wxFileSystem>	fileSystem(new wxFileSystem);
    std::auto_ptr<wxFSFile>     file(fileSystem->OpenFile(file_res));
    if( file.get() ){
        wxMemoryInputStream memStream(*file->GetStream());
        wxImage image(memStream, wxBITMAP_TYPE_ANY, -1);
        if( image.IsOk() ){
            wxBitmap bitmap(image, -1);
            return bitmap;
        }
    }

	return wxBitmap();
}

wxBitmap LoadBitmapFromFile( const wxString& name )
{
    wxString file_res = _T("./") + name;

    std::auto_ptr<wxFileSystem>	fileSystem(new wxFileSystem);
    std::auto_ptr<wxFSFile>     file(fileSystem->OpenFile(file_res));
    if( file.get() ){
        wxMemoryInputStream memStream(*file->GetStream());
        wxImage image(memStream, wxBITMAP_TYPE_ANY, -1);
        if( image.IsOk() ){
            wxBitmap bitmap(image, -1);
            return bitmap;
        }
    }

    throw std::exception("invalid image. [" + name + "]");
}

bool wxDeleteTree(const wxString & dir_s)
{
    class wxDirTraverserSimple : public wxDirTraverser
    {
    public:
        virtual wxDirTraverseResult OnDir(const wxString& dirname)
        {
            wxDeleteTree(dirname);
            return wxDIR_IGNORE;
        }
        virtual wxDirTraverseResult OnFile(const wxString& filename)
        {
            wxRemoveFile(filename);
            return wxDIR_CONTINUE;
        }
    };

    if( wxDirExists(dir_s) ){
        wxDirTraverserSimple traverser;
        wxDir dir(dir_s);
        dir.Traverse(traverser);
        return wxRmdir(dir_s);
    }
    return true;
}

bool fuMakeDirPath(const std::string & path)
{
    std::string dir_path = cppx::fuStringHelper(path).ReplaceAll("\\","/");
    if( wxDirExists(dir_path.c_str()) )
        return true;

    size_t pos = dir_path.find_last_of('/',-1); // npos is not linkable
    std::string dir_parent = dir_path.substr(0,pos);
    if( fuMakeDirPath(dir_parent) )
        return wxMkdir(dir_path.c_str());

    return false;
}

bool fuMoveFile(const std::string & file_src,const std::string & file_dst,bool over_write /*= true*/)
{
    wxFileName filename(file_dst.c_str());
    if( fuMakeDirPath((const char*)filename.GetPath()) )
        return wxRenameFile(file_src.c_str(),file_dst.c_str(),over_write);
    return false;
}
